﻿using System;
using System.Threading;

namespace TaggingToolkit.Interprocess
{
    public static class InstanceManager
    {
        static Mutex mutex;

        public static void Register(string identifier)
        {
            if (string.IsNullOrEmpty(identifier)) throw new InvalidOperationException($"{nameof(identifier)} can't be nothing");
            if (mutex != null) throw new InvalidOperationException("already initialized");

            mutex = new Mutex(true, identifier);
        }

        public static void Unregister()
        {
            if (mutex == null) throw new InvalidOperationException("can't unregister nothing");

            mutex.Close();
            mutex = null;
        }

        public static bool IsAlreadyRunning()
        {
            bool result;
            if (mutex.WaitOne(TimeSpan.Zero, true))
            {
                result = false;
                mutex.ReleaseMutex();
            }
            else
            {
                result = true;
            }
            return result;
        }

        public static string CreateMutexName(string mutexName)
        {
#if DEBUG
            mutexName += "DEBUG";
#else
            mutexName += "RELEASE";
#endif

#if _X64
            mutexName += "X64";
#else
            mutexName += "ANYCPU";
#endif
            return mutexName;
        }
    }
}
